#
# graphTimeInconsistency.R
#
# Make graphs of CCES 2014 time inconsistency
# result.
#
# Seth Hill, 2018
#

rm(list=ls())
if (.Platform$OS == "windows") {
  # Set working directory in location of script.
  .doit <- function() { # only works with R.exe; trap errors if using Rscript.exe
  frame_files <- lapply(sys.frames(), function(x) x$ofile);frame_files <- Filter(Negate(is.null), frame_files)
  PATH <- dirname(frame_files[[length(frame_files)]]); setwd(PATH) ; rm(PATH,frame_files)
  }
  try(.doit(),silent=T)
}
library(bit64)
library(data.table)
options(stringsAsFactors=F)
library(foreign)
library(survey)

# %%%%%%%%%%%%%%
# Call in data, outsheeted from
# analyzeTimeInconsistency.do. 
# %%%%%%%%%%%%%%
dat <- read.dta("Recoded-CCESTurnoutData.dta")
# Create survey design object.
sv  <- svydesign(id=~V101,weights=~weight,data=dat)

pdf("Fig01.pdf",height=6,width=8)
par(mar=c(3.1,4.1,1.1,1.1),cex.lab=1.2,cex.axis=1.2)
# Bar plot 1.
# Tabs of turnout by present bias.
tab1 <- svyby(~voted_vv+pvoted_vv,~hyperb_disc,design=sv,svymean,na.rm=T)
.myBarPlot <- function(tab1,row.names=c("Not present biased","Present biased"),ylab="Turnout 2014",cols=c("voted_vv","pvoted_vv"),col.names=c("Validated general","Validated primary"), space=c(0,0.5), ylim=NULL, ...) {
  bar.mat <- as.matrix(tab1[,cols])
  rownames(bar.mat) <- row.names
  colnames(bar.mat) <- col.names
  # Create confidence bars.
  bar.mat.ub <- bar.mat + 1.96*as.matrix(tab1[,sprintf("se.%s",cols)])
  bar.mat.lb <- bar.mat - 1.96*as.matrix(tab1[,sprintf("se.%s",cols)])

  # Bar plot.
  if (is.null(ylim)) {
    ylim <- range(c(0,bar.mat.ub,bar.mat.lb))
  }
  z <- barplot(height=bar.mat, beside=T, main="", ylab=ylab, xlab="", legend.text=T, space=space, col=gray(seq(.4,.95,length.out=nrow(bar.mat))), axes=F, ylim=ylim,...)
  # Add error bars.
  segments(x0=z, y0=bar.mat.ub, y1=bar.mat.lb, lwd=1)
  arrows(x0=z, y0=bar.mat.ub, y1=bar.mat.lb, lwd=1, angle=90, code=3, length=0.05)
  axis(2,las=2)
}
.myBarPlot(tab1,col.names=c("General election","Primary election"))

# Bar plot 2.
# Tabulation of follow through among those intending to vote.
sv.intend <- subset(sv,CC354 == "Yes, definitely")
tab3 <- svyby(~voted_vv+pvoted_vv,~hyperb_disc,design=sv.intend,svymean,na.rm=T)
.myBarPlot(tab3,ylab="Followed through on intention to vote",cols=c("voted_vv"),col.names=c(""), space=c(0.5,0.5),ylim=c(0,1))

dev.off()

